package io.gitee.zhangbinhub.acp.cloud.loadbalancer

import org.noear.solon.cloud.impl.CloudLoadStrategy
import org.noear.solon.cloud.model.Discovery
import org.noear.solon.cloud.model.Instance
import org.noear.solon.core.handle.Context

class AcpNacosLoadBalancer(
    private val acpServiceInstanceFilters: MutableList<AcpServiceInstanceFilter>,
    private val acpLoadBalancerAlgorithmMap: MutableMap<String, AcpLoadBalancerAlgorithm>
) : CloudLoadStrategy {
    override fun getServer(discovery: Discovery, port: Int): String? {
        val context: Context? = Context.current()
        return discovery.clusterOf(port).let {
            var filteredInstances: MutableList<Instance> = it
            acpServiceInstanceFilters.forEach { filter ->
                filteredInstances = filter.filterInstance(context, filteredInstances)
            }
            filteredInstances
        }.let { filteredInstances ->
            try {
                if (acpLoadBalancerAlgorithmMap.containsKey(discovery.service())) {
                    acpLoadBalancerAlgorithmMap[discovery.service()]?.getInstance(context, filteredInstances)
                } else {
                    acpLoadBalancerAlgorithmMap[AcpLoadBalancerAlgorithm.DEFAULT_SERVICE_ID]?.getInstance(
                        context,
                        filteredInstances
                    )
                }
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }?.uri()
    }
}